<template>
  <a-card :bordered="false" class="card-area">
    <div class="table-page-search-wrapper"  v-if="!visible">
      <a-form layout="vertical">
        <a-row :gutter="48">
          <a-col :sm="{span:24}" :lg="{span:12}" :xl="{span:6}" >
            <a-form-item label="学号">
               <a-input placeholder="请输入..." v-model="queryParam.xh"/>
            </a-form-item>
          </a-col>
          <a-col :sm="{span:24}" :lg="{span:12}" :xl="{span:6}" >
            <a-form-item label="姓名">
               <a-input placeholder="请输入..." v-model="queryParam.xm"/>
            </a-form-item>
          </a-col>
          <a-col :sm="{span:24}" :lg="{span:12}" :xl="{span:6}" >
            <a-form-item label="年级">
              <a-select  :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.zsnd">
                <a-select-option v-for="i in TYPE0126" :key="i.id" :value="i.code">{{i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
           <a-col :sm="{span:24}" :lg="{span:12}" :xl="{span:6}" >
            <a-form-item label="院系">
              <a-select :disabled="selectMenu.yx.length === 1" :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.yxm" @change="yxChange">
                <a-select-option v-for="i in selectMenu.yx" :key="i.id" :value="i.dwh">{{i.dwh+"-"+  i.dwmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="{span:24}" :lg="{span:12}" :xl="{span:6}" >
            <a-form-item label="专业">
              <a-select :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.zym" >
                <a-select-option v-for="i in selectMenu.zy" :key="i.zyh" :value="i.zyh">{{ i.zyh+'-'+i.zymc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
           <a-col :sm="{span:24}" :lg="{span:12}" :xl="{span:6}" >
            <a-form-item label="学生类别">
              <a-select  :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.pyccm" >
                <a-select-option v-for="i in TYPE0310" :key="i.id" :value="i.code">{{i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="{span:24}" :lg="{span:12}" :xl="{span:6}" >
            <a-form-item label="奖学金类型">
              <a-select  :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.jxjdjdm">
                <a-select-option v-for="i in TYPE_jxjlx" :key="i.id" :value="i.code">{{i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
       <!--   <a-col :sm="{span:24}" :lg="{span:12}" :xl="{span:6}">
            <a-form-item label="科目类型">
              <a-select :allowClear="true" showSearch optionFilterProp="children" v-model="queryParam.kmlxm">
                <a-select-option v-for="i in selectMenu.kmlx" :key="i.code" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          </template>
          <a-col :sm="{span:16}" :xl="{span:16}">
            <span class="table-page-search-submitButtons" >
            <a-button type="primary" @click="modelShow = true">发起奖学金申请</a-button>
            <a-button type="primary" @click="loadData">查询</a-button>
            <!-- <a-button type="primary" @click="exportExcel">导出</a-button> -->
            <a-button type="primary" @click="handleBatchDelete">批量删除</a-button>
              <a-button @click="queryParam = {};$refs.table.refresh()">重置</a-button>

            <a @click="advanced = !advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <a-table
    v-if="!visible"
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :loading="loading"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      :dataSource="data"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template slot="action" slot-scope="text,record">
        <a @click="handleEdit(record.id,record.xh)">修改</a>
        <a @click="handleDelete(record.id)">删除</a>
      </template>
      <template slot="kmmc" slot-scope="text,record">
        <a @click="handlePreview(record.id)">{{text}}</a>
      </template>

      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
    </a-table>

    <a-modal
      title="请输入需申请奖学金的学号"
      :visible="modelShow"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form layout="vertical">
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-item>
              <a-input placeholder="请输入需申请奖学金的学号" v-model="queryParam.studentId"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <div v-if="visible">
      <a-form :form='form'>
        <a-row :gutter="48">
            <a-col :md="6" :sm="12">
            <div>学号：{{user.xh}}</div>
          </a-col>
          <a-col :md="6" :sm="12">
            <div>姓名：{{user.xm}}</div>
          </a-col>
          <a-col :md="6" :sm="12">
            <div>性别：{{user.xbmc}}</div>
          </a-col>
          <a-col :md="6" :sm="12">
            <div>年级：{{user.xjxx.sznj}}</div>
          </a-col>
          <a-col :md="6" :sm="12">
            <div>院系：{{user.xjxx.ssyxmc}}</div>
          </a-col>
          <a-col :md="6" :sm="12">
            <div>专业：{{user.xjxx.sszymc}}</div>
          </a-col>
          
          <a-col :md="6" :sm="12">
            <div>学生类别：{{user.xjxx.xslbmc}}</div>
          </a-col>
          <a-col :md="6" :sm="12">
            <div>证件类型：{{user.sfzjlxmc}}</div>
          </a-col>
          <a-col :md="6" :sm="12">
            <div>证件号码：{{user.zjhm}}</div>
          </a-col>
          </a-row>
          <a-row :gutter="48">
          <a-col :md="6" :sm="12">
            <a-form-item label="学年" :labelCol="{span: 24,offset: 0}" :wrapperCol="{span: 24}">
              <a-select :allowClear="true" disabled v-decorator="['xn',{ rules: [{ required: true, message: '请选择学年' }]}]">
                <a-select-option v-for="i in TYPE0126" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="奖学金类型" :labelCol="{span: 24,offset: 0}" :wrapperCol="{span: 24}">
              <a-select :allowClear="true" v-decorator="['jxjdj',{ rules: [{ required: true, message: '请选择奖学金级别' }]}]" @change="jbChange">
                <a-select-option v-for="i in jxjpz" :key="i.id" :value="i.jxjdjdm">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="奖学金级别" :labelCol="{span: 24,offset: 0}" :wrapperCol="{span: 24}">
              <a-select :allowClear="true" v-decorator="['jxjlxm',{ rules: [{ required: true, message: '请选择奖学金类型' }]}]">
                <a-select-option  v-for="i in selectMenu.lx" :key="i.id" :value="i.jxjlxm">{{ i.jxjlxmmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="银行卡号" :labelCol="{span: 24,offset: 0}" :wrapperCol="{span: 24}">
                <a-input type="text" v-decorator="[
                  'jxjkh',
                  {
                    rules: [{ required: true, message: '请输入银行卡号' }],
                  }
                ]"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <!-- <a-row>
          <a-form-item label="备注" :labelCol="{span: 24,offset: 0}" :wrapperCol="{span: 24}">
              <a-input type="textarea" v-decorator="[
                  'leaveRemark',
                  {
                    rules: [{ required: false, }],
                  }
                ]" :autosize="{ minRows: 6, maxRows: 10 }"/>
            </a-form-item>
        </a-row> -->
        <a-row style="text-align: center">
          <a-button type="primary" @click="sub">提交</a-button>
          <a-button type="primary" @click="visible=false">关闭</a-button>
        </a-row>
      </a-form>
    </div>
    <!-- 新增 -->
    <!-- <study-add ref="referenceAdd" @close="handleCreateClose" @success="handleCreateSuccess" :referenceManageAddVisiable="referenceManageAddVisiable"></study-add> -->
    <!-- <reference-add ref="referenceAdd" @close="handleCreateClose" @success="handleCreateSuccess" :referenceManageAddVisiable="referenceManageAddVisiable"></reference-add> -->
    <!-- 编辑 -->
    <setup-edit ref="referenceEdit" @close="handleEditClose" @success="handleEditSuccess" :info="referenceManageEditData"  :referenceManageEditVisiable="referenceManageEditVisiable"></setup-edit> 
    <!-- <reference-edit ref="referenceEdit" @close="handleEditClose" @success="handleEditSuccess" :info="referenceManageEditData"  :referenceManageEditVisiable="referenceManageEditVisiable"></reference-edit> -->
    <!-- 详情 -->
    <!-- <reference-detail ref="referenceDetail" :info="preViewData" ></reference-detail> -->
  </a-card>
</template>

<script>
// import moment from 'moment'
// import ReferenceAdd from './referenceAdd'
// import ReferenceEdit from './referenceEdit'
// import ReferenceDetail from '../reference/referenceDetail'
// import studyAdd from './studyAdd'
import setupEdit from './setupEdit'
import { STable } from '~'
import { mapState } from 'vuex'

const selectArr = ['TYPE0126', 'TYPE0310', 'TYPE_jxjlx', 'TYPE0072','TYPE0125','TYPE0311','TYPE0312']

export default {
  components: {
    STable,
    // studyAdd,
    setupEdit
    // ReferenceAdd,
    // ReferenceEdit,
    // ReferenceDetail
  },
  data () {
    return {
      advanced: true,
      loading: false,
      data: [],
      id:'',
      // 查询参数
      queryParam: {
        yxm:''
      },
      postParams: {},
      // 表头
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '学号',
          dataIndex: 'xh'
        },
        {
          title: '姓名',
          dataIndex: 'xm',
        },
        {
          title: '年级',
          dataIndex: 'sznj'
        },
        {
          title: '院系',
          dataIndex: 'yxm'
        },
        {
          title: '专业',
          dataIndex: 'zym'
        },
        {
          title: '学生类别',
          dataIndex: 'pyccm'
        },
        
        {
          title: '奖学金类型',
          dataIndex: 'jxjdj'
        },
        {
          title: '奖学金级别',
          dataIndex: 'jxjlxm'
        },
        {
          title: '卡号',
          dataIndex: 'jxjkh'
        },
        {
          title: '奖学金金额',
          dataIndex: 'je'
        },
        {
          title: '操作',
          dataIndex: 'cz',
          fixed: 'right',
          width: 120,
          scopedSlots: { customRender: 'action' }
        }
      ],
      selectedRowKeys:[],
      selectedRows:[],
      options: {
         alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
         rowSelection: {
           selectedRowKeys: this.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
             console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
             this.selectedRowKeys = selectedRowKeys
             this.selectedRows = selectedRows
           },
           onSelect: (record, selected, selectedRows) => {
             console.log(record, selected, selectedRows)
           },
           onSelectAll: (selected, selectedRows, changeRows) => {
             console.log(selected, selectedRows, changeRows)
           },
         }
       },
      referenceManageAddVisiable: false,
      referenceManageEditVisiable: false,
      selectMenu: {
        yx: [] ,// 院系
        kmlx:[]
      },
      referenceManageEditData: {},
      preViewData: {},
      pagination: {
        current: 1
      },
      visible:false,
      modelShow:false,
      confirmLoading: false,
      user:{},
      jxjpz:[],
      list:[]
    }
  },
  computed: {
    ...mapState({
      systemInfo: state => state.app.systemInfo,
      TYPE0126: state => state.app['TYPE0126'], // 年级
      TYPE0310: state => state.app['TYPE0310'],
      TYPE_jxjlx: state => state.app['TYPE_jxjlx'],
      TYPE0125: state => state.app['TYPE0125'],
       TYPE0311: state => state.app['TYPE0311'],
       TYPE0312: state => state.app['TYPE0312'],
    })
  },
   beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  created () {
    this.initSelectMenu()
    selectArr.forEach(v => {
      this.$store.dispatch('app/setDictionary', v)
    })
  },
  methods: {
    initSelectMenu () {
      let allRequest = [
        this.$api.base.collegeAll()
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yx: res[0].data
        }
        this.queryParam.yxm = res[0].data[0].dwh
        this.$api.base.dictionaryData('TYPE0430').then(res => {
            this.selectMenu.kmlx = res.data
        })
        this.loadData({
          pageSize: 10,
          pageNum: 1
        })
      })
    },
     // 加载数据
    loadData(parameter = {}) {
      if(!parameter.pageNum){
        this.pagination.current = 1
        parameter.pageNum = 1
      }
      let params = Object.assign(this.queryParam, parameter)
      this.loading = true;
      this.$api.student.scholarshipList(params).then(res => {
        // console.log(res)
         const pagination = { ...this.pagination
        };
        pagination.total = 0
        if (res.data && res.data.total) {
          pagination.total = res.data.total;
        }
        this.data = []
        this.pagination = pagination;
        if (res.data.rows && res.data.rows.length) {
          this.data = res.data.rows;
        }
        this.loading = false;
      })
    },
    handleOk(){
      this.$api.base.getSchoolYear().then(res =>{
        this.$nextTick(() =>{
          this.form.getFieldDecorator('xn',{initialValue:res.data.schoolYear})
        })
      })
      this.$api.student.scholarshipBase(this.queryParam.studentId).then(res => {
          
          if(res.data.jxjpz){
              this.jxjpz = []
          this.visible = true
          this.modelShow = false
          this.user = res.data.xsxx
            this.postParams = res.data.jxjpz[0]
            this.postParams.pycc = res.data.xsxx.xjxx.pyccm
            this.postParams.yxm = res.data.xsxx.xjxx.ssyxm
            this.postParams.zsnj = res.data.xsxx.xjxx.sznj
            this.TYPE_jxjlx.forEach(item =>{
              res.data.jxjpz.forEach(it => {
                if(it.jxjdjdm == item.code){
                  it.name = item.name
                  this.jxjpz.push(it)
                }
              })
            })
            this.$nextTick(()=>{
           
             if(res.data.jxjpz[0].jxjdjdm){
             this.form.setFieldsValue({jxjdj:this.jxjpz[0].jxjdjdm})
             }
             })
             let params ={
               ssyxm:this.postParams.yxm,
               zsnd:this.postParams.zsnj,
               pyccm:this.postParams.pycc,
               jxjdjdm:this.postParams.jxjdjdm
             }
             
             this.$api.student.setupList(params).then(result =>{
                 this.list = result.data.rows
                 this.$set(this.selectMenu,'lx',result.data.rows)
             })
          }else {
              this.$message.warning('请输入正确的学号')
              
          }
        //    this.form.setFieldsValue({jxjdj:this.TYPE_jxjlx[0].code})
        //      if(this.TYPE_jxjlx[0].code == '1'){
        //         this.$set(this.selectMenu,'lx',this.TYPE0311)
        //      }else {
        //        this.$set(this.selectMenu,'lx',this.TYPE0312)
        //      }
        }).catch(e => {
          
        })
    },
    handleCancel(e) {
      this.modelShow = false;
    },
    // 分页
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      const pager = { ...this.pagination
      };
      pager.current = pagination.current;
      this.pagination = pager;
      this.loadData({
        pageSize: 10,
        pageNum: pagination.current
      });
    },
     // 多选
    onSelectChange (selectedRowKeys,selectedRows) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
    },
    // 选择院系
    yxChange (code) {
      this.$set(this.queryParam, 'zym', '')
      this.$api.base.majorAll({lsdwh: code}).then(res => {
        this.$set(this.selectMenu, 'zy', res.data)
      })
    },
    // 添加
    handleCreate () {
      this.referenceManageAddVisiable = true
    },
    // 关闭添加弹层
    handleCreateClose () {
      this.referenceManageAddVisiable = false
    },
    // 添加成功
    handleCreateSuccess () {
      this.referenceManageAddVisiable = false
      this.$message.success('添加成功')
      this.loadData({
        pageSize:10,
        pageNum:this.pagination.current
      })
    },
    // 查看详情
    handlePreview (key) {
      this.$api.recruitstat.entrySubjectManageId(key).then( res => {
           this.preViewData = res.data
            this.$refs.referenceDetail.show()
      })
    },
    // 修改
    handleEdit (key,xh) {
        Promise.all([this.$api.student.scholarshipId(key), this.$api.student.scholarshipBase(xh)]).then(res =>{
            console.log(res)
            if(res[0].data){
              this.visible = true
              this.$nextTick(()=>{
              this.form.setFieldsValue({xn:res[0].data.xn})
              this.form.setFieldsValue({jxjdj:res[0].data.jxjdj})
              this.form.setFieldsValue({jxjlxm:res[0].data.jxjlxm})
              this.form.setFieldsValue({jxjkh:res[0].data.jxjkh})
              })
              this.id = key;
            }
            if(res[1].data.jxjpz){
            this.jxjpz = []
            this.user = res[1].data.xsxx
            this.postParams = res[1].data.jxjpz[0]
            this.postParams.pycc = res[1].data.xsxx.xjxx.pyccm
            this.postParams.yxm = res[1].data.xsxx.xjxx.ssyxm
            this.postParams.zsnj = res[1].data.xsxx.xjxx.sznj
            this.TYPE_jxjlx.forEach(item =>{
              res[1].data.jxjpz.forEach(it => {
                if(it.jxjdjdm == item.code){
                  it.name = item.name
                  this.jxjpz.push(it)
                }
              })
            })
             let params ={
               ssyxm:this.postParams.yxm,
               zsnd:this.postParams.zsnj,
               pyccm:this.postParams.pycc,
               jxjdjdm:res[0].data.jxjdj
             }
             this.$api.student.setupList(params).then(result =>{
                 this.list = result.data.rows
                 this.$set(this.selectMenu,'lx',result.data.rows)
             })
          }
        })
      
    },
    // 关闭添加弹层
    handleEditClose () {
      this.referenceManageEditVisiable = false
    },
    // 添加成功
    handleEditSuccess () {
      this.referenceManageEditVisiable = false
      this.$message.success('修改成功')
      this.loadData({
        pageSize:10,
        pageNum:this.pagination.current
      })
    },
    // 导出
    exportExcel () {
      console.log('导出')
      this.$export('admissions/zsSsckkm/export', this.queryParam)
    },
    // 删除
    handleDelete (key) {
      console.log('删除')
      var that = this;
      this.$confirm({
        title: '确定删除?',
        onOk() {
          console.log('OK');
          that.deleteData(key)
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
    },
    // 批量删除
    handleBatchDelete () {
      console.log('批量删除')
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的数据')
        return
      }
      var deleteId
      if (this.selectedRows && this.selectedRows.length){
        deleteId = this.selectedRows.map(v => {
          return v.id
        }).toString()
      }
      console.log(deleteId)
       var that = this;
       this.$confirm({
         title: '确定删除?',
         onOk() {
           console.log('OK');
           that.deleteData(deleteId)
         },
         onCancel() {
           console.log('Cancel');
         },
         class: 'test',
       });
    },
    deleteData(id){
      this.$api.student.scholarshipDel(id).then( res => {
        this.loadData({
          pageSize:10,
          pageNum:this.pagination.current
        })
        this.selectedRowKeys = []
      })
    },
    sub () {
      const form = this.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        // this.$api.student.transfering(this.$DateToString(Object.assign({xh: this.user.xh}, values))).then(res => {
        //   this.$refs.table.refresh(true)
        // })
        // let fileName = this.user.xm + '_外宿申请单.pdf'
        let jxjsdxxid = ''
        this.list.forEach(item => {
          if(item.jxjlxm == values.jxjlxm){
            jxjsdxxid = item.id
          }
        })
        let params = Object.assign(values)
        params.xh = this.user.xh
        params.jxjsdxxid = jxjsdxxid
        this.$DateToString(params)
        if(this.id){
            params.id = this.id
            this.$api.student.scholarshipUpdate(params).then(res => {
          form.resetFields()
          this.visible = false
        }).catch(e => {
          this.$message.warn(e.msg)
          // this.visible = false
          // this.$refs.table.refresh(true)
          // form.resetFields()
        })
        }else{
        this.$api.student.scholAdd(params).then(res => {
          form.resetFields()
          this.visible = false
        }).catch(e => {
          this.$message.warn(e.msg)
          // this.visible = false
          // this.$refs.table.refresh(true)
          // form.resetFields()
        })
        }
        
        
      })
    },
    jbChange(code){
        this.$set(this.selectMenu,'lx',[])
        // console.log(this.$store.state.app['0311'])
        // console.log(this.$store.state.app['0312'])
        this.form.setFieldsValue({jxjlxm:''})
        if(code){
          let params ={
               ssyxm:this.postParams.yxm,
               zsnd:this.postParams.zsnj,
               pyccm:this.postParams.pycc,
               jxjdjdm:code
             }
             this.$api.student.setupList(params).then(result =>{
                 this.list = result.data.rows
                 this.$set(this.selectMenu,'lx',result.data.rows)
             })
        }
        console.log(this.selectMenu.lx)
    }
  }
}
</script>
